package logger

import (
	"fmt"
	"gin-fileserver/pkg/file"
	"gin-fileserver/pkg/setting"
	"os"
	"path"
	"time"

	log "github.com/sirupsen/logrus"
)

var logFile *os.File

func getSavePath() string {
	p := path.Join(setting.Cfg.AppSetting.RuntimePath, setting.Cfg.AppSetting.LogFilePath)
	if err := file.IsNotExistMkDir(p); err != nil {
		log.Panicln(p)
	}
	return p
}

func Setup() {
	var err error
	// open a file
	filename := fmt.Sprintf("%s.log", time.Now().Format("20060102"))
	logFile, err = os.OpenFile(path.Join(getSavePath(), filename), os.O_APPEND|os.O_CREATE|os.O_RDWR, 0666)
	if err != nil {
		log.Printf("error opening file: %v", err)
	}
	// Log as JSON instead of the default ASCII formatter.
	log.SetFormatter(&log.JSONFormatter{})

	// Output to stderr instead of stdout, could also be a file.
	log.SetOutput(logFile)

	// Only log the warning severity or above.
	log.SetLevel(log.DebugLevel)
}

func Close() {
	logFile.Close()
}
